<!DOCTYPE html>
<html lang="zh-CN">
<head>

  <meta charset="UTF-8">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{% block title %}OnlineJudge{% endblock %}</title>

  <!-- 外部资源 -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" 
      integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" 
      crossorigin="anonymous" referrerpolicy="no-referrer" /> -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="icon" type="image/png" href="{{ url_for('static', filename='images/logo.png') }}">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" 
        integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" 
        crossorigin="anonymous" referrerpolicy="no-referrer" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

  <!-- Tailwind 配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            success: '#00B42A',
            warning: '#FF7D00',
            danger: '#F53F3F',
            dark: '#1D2129',
            'dark-2': '#4E5969',
            'light-1': '#F2F3F5',
            'light-2': '#E5E6EB',
          },
          fontFamily: {
            inter: ['Inter', 'sans-serif'],
          },
        }
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto { content-visibility: auto; }
      .text-shadow { text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }
      .card-hover { transition: all 0.3s ease; }
      .card-hover:hover { 
        transform: translateY(-5px); 
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); 
      }
      .btn-primary { 
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 
               hover:bg-primary/90 focus:ring-2 focus:ring-primary/50 focus:outline-none; 
      }
      .btn-secondary { 
        @apply bg-white text-dark border border-light-2 px-4 py-2 rounded-lg transition-all duration-300 
               hover:bg-light-1 focus:ring-2 focus:ring-light-2 focus:outline-none; 
      }
      .btn-danger { 
        @apply bg-danger text-white px-4 py-2 rounded-lg transition-all duration-300 
               hover:bg-danger/90 focus:ring-2 focus:ring-danger/50 focus:outline-none; 
      }
      .form-input { 
        @apply w-full px-4 py-2 rounded-lg border border-light-2 focus:border-primary focus:ring-2 focus:ring-primary/20 
               transition-all duration-300 outline-none; 
      }
      .nav-link { 
        @apply text-dark flex items-center space-x-2 text-base font-medium 
               hover:text-primary transition-colors duration-300; 
      }
      .nav-link.active { @apply text-primary border-b-2 border-primary pb-1; }
      #user-menu-container { @apply relative w-40; }
      #user-menu-button { 
        @apply flex items-center space-x-2 w-full px-3 py-2 rounded-md border border-light-2 bg-white 
               hover:bg-light-1 transition-colors duration-300; 
      }
      #user-menu { 
        @apply absolute right-0 mt-2 z-10 w-40 bg-white border border-light-2 rounded-md shadow shadow-md; 
      }
      #user-menu a { 
        @apply flex items-center space-x-2 px-3 py-2 text-sm text-dark 
               hover:bg-light-1 transition-colors duration-300; 
      }
      .flash-toast { 
        @apply fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 
               rounded-lg shadow-lg p-6 text-center z-50 
               opacity-0 scale-95 transition-all duration-300; 
      }
      .flash-toast.show { @apply opacity-100 scale-100; }
      .flash-toast.success { @apply bg-success/10 border border-success/30 text-success/80; }
      .flash-toast.danger { @apply bg-danger/10 border border-danger/30 text-danger/80; }
      .flash-toast.warning { @apply bg-warning/10 border border-warning/30 text-warning/80; }
    }
  </style>
</head>

<body class="font-inter bg-gray-50 text-dark min-h-screen flex flex-col">

  <!-- 导航栏（通过 hide_nav 控制显示） -->
  {% if not hide_nav %}
  <nav class="bg-white shadow-md sticky top-0 z-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex items-center h-16">
      <!-- 左侧Logo和导航 -->
      <div class="flex items-center space-x-6">
        <a href="{% if current_user.is_authenticated and current_user.username == 'root' %}{{ url_for('admin_dashboard') }}{% else %}{{ url_for('problems') }}{% endif %}" class="flex-shrink-0 flex items-center">
          <i class="fas fa-code text-primary text-2xl mr-2"></i>
          <span class="text-xl font-bold text-dark">Online Judge</span>
        </a>
      </div>

      <!-- 右侧用户菜单 -->
      <div class="ml-auto flex items-center">
        {% if user %}
        <div id="user-menu-container">
          <button type="button" id="user-menu-button" class="flex items-center space-x-2">
            {% if user.avatar %}
              <img 
                src="{{ url_for('static', filename='uploads/avatars/' + user.avatar) }}" 
                alt="用户头像" 
                class="w-6 h-6 rounded-full object-cover"
              >
            {% else %}
              <img 
                src="{{ url_for('static', filename='uploads/avatars/default.jpg') }}" 
                alt="默认头像" 
                class="w-6 h-6 rounded-full object-cover"
              >
            {% endif %}
            <span class="text-sm font-medium">{{ user.username }}</span>
          </button>
          <div class="hidden" id="user-menu">

          <!-- 个人设置：仅非游客可见 -->
          {% if current_user.is_authenticated and current_user.username != 'root' %}
          <a href="{{ url_for('user_settings') }}">
            <i class="fas fa-cog text-base"></i>  个人设置
          </a>
          {% endif %}

          <!-- 退出登录：所有登录用户可见（包括游客） -->
          <a href="#" onclick="logout()">
            <i class="fas fa-sign-out text-base"></i>  退出登录
          </a>
        </div>
        </div>
        {% else %}
        <a href="{{ url_for('login') }}" class="text-dark-2 hover:text-primary mr-3">登录</a>
        <a href="{{ url_for('register') }}" class="btn-primary">注册</a>
        {% endif %}
      </div>
    </div>
  </nav>
  {% endif %}

  <!-- 主内容区 -->
  <main class="flex-grow">
    <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
      <!-- 全局弹窗 -->
      <div id="flash-toast" class="flash-toast"></div>
      
      {% block content %}
      <p class="text-center text-gray-500">加载中...</p>
      {% endblock %}
    </div>
  </main>

  <!-- 全局删除确认模态框 -->
  <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content rounded-lg shadow-lg border-0">
        <div class="modal-header bg-light-1 rounded-t-lg">
          <h5 class="modal-title text-lg font-semibold text-dark" id="deleteModalLabel">确认删除</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body p-6">
          <p class="text-dark-2">确定要删除题目《<span id="problemTitle" class="font-medium text-dark">未知题目</span>》吗？删除后无法恢复！</p>
        </div>
        <div class="modal-footer bg-light-1/50 rounded-b-lg p-4 flex justify-end gap-3">
          <button type="button" class="btn-secondary" data-bs-dismiss="modal">取消</button>
          <form id="deleteForm" method="post" action="">
            <!-- 👇 添加 CSRF 令牌 👇 -->
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button type="submit" class="btn-danger">确认删除</button>
          </form>
        </div>
      </div>
    </div>
  </div>

  <!-- 页脚（通过 hide_nav 控制显示） -->
  {% if not hide_nav %}
  <footer class="bg-dark text-white py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex flex-col md:flex-row items-center justify-center">
        <div class="mb-4 md:mb-0">
          <div class="flex items-center">
            <i class="fas fa-code text-primary text-2xl mr-2"></i>
            <span class="text-xl font-bold">Online Judge</span>
          </div>
          <p class="text-gray-400 mt-2">一个简单的在线判题系统</p>
        </div>
      </div>
      <div class="border-t border-gray-800 mt-8 pt-8 text-center text-gray-400">
        <p>&copy; 2025 Online Judge. 保留所有权利。</p>
      </div>
    </div>
  </footer>
  {% endif %}

  <!-- 核心脚本 -->
  <script>
    // 用户菜单切换
    document.getElementById('user-menu-button')?.addEventListener('click', () => {
      const menu = document.getElementById('user-menu');
      menu?.classList.toggle('hidden');
    });

    // 点击空白处关闭用户菜单
    document.addEventListener('click', (e) => {
      const menuContainer = document.getElementById('user-menu-container');
      const menu = document.getElementById('user-menu');
      if (menuContainer && !menuContainer.contains(e.target)) {
        menu?.classList.add('hidden');
      }
    });

    // 导航激活态
    document.addEventListener('DOMContentLoaded', () => {
      const navLinks = document.querySelectorAll('.nav-link');
      navLinks.forEach(link => {
        if (link.href === window.location.href) {
          link.classList.add('active');
        }
      });
      const userMenuItems = document.querySelectorAll('#user-menu a');
      userMenuItems.forEach(item => {
        if (item.href === window.location.href) {
          item.classList.add('bg-light-1');
        }
      });
    });

    // 退出登录
    function logout() {
      alert('退出登录成功');
      window.location.href = "{{ url_for('login') }}";
    }

    // 全局弹窗逻辑
    document.addEventListener('DOMContentLoaded', () => {
      const flashToast = document.getElementById('flash-toast');
      const flashMessage = document.createElement('div');
      flashMessage.id = 'flash-message';
      flashMessage.className = 'text-lg font-medium';
      flashToast.appendChild(flashMessage);

      const messages = {{ get_flashed_messages(with_categories=true) | tojson }};
      messages.forEach(([category, rawMsg]) => {
        try {
          const msgData = JSON.parse(rawMsg);
          flashMessage.innerHTML = msgData.message.replace('{count}', `<span id="countdown">${msgData.count || 3}</span>`);
          flashToast.className = `flash-toast ${category} show`;

          if (msgData.password_changed) {
            const countdownEl = document.getElementById('countdown');
            let count = parseInt(msgData.count) || 3;
            const timer = setInterval(() => {
              count--;
              countdownEl.textContent = count;
              if (count <= 0) {
                clearInterval(timer);
                window.location.href = "{{ url_for('login') }}";
              }
            }, 1000);
          } else {
            setTimeout(() => {
              flashToast.classList.remove('show');
            }, 3000);
          }
        } catch (e) {
          flashMessage.textContent = rawMsg;
          flashToast.className = `flash-toast ${category} show`;
          setTimeout(() => {
            flashToast.classList.remove('show');
          }, 3000);
        }
      });
    });

    // 点击空白处关闭弹窗
    document.addEventListener('click', (e) => {
      const flashToast = document.getElementById('flash-toast');
      if (flashToast?.classList.contains('show') && !flashToast.contains(e.target)) {
        flashToast.classList.remove('show');
      }
    });

    // 删除确认模态框逻辑
    document.addEventListener('DOMContentLoaded', () => {
      // 初始化全局模态框
      const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
      
      // 监听所有删除按钮的点击事件
      document.querySelectorAll('[data-bs-target="#deleteModal"]').forEach(btn => {
        btn.addEventListener('click', (e) => {
          e.preventDefault(); // 阻止默认跳转行为
          
          // 提取按钮上的自定义数据
          const problemId = btn.getAttribute('data-problem-id');
          const problemTitle = btn.getAttribute('data-problem-title');
          
          // 动态更新模态框内容
          if (problemTitle) {
            document.getElementById('problemTitle').textContent = problemTitle;
          }
          
          // 设置表单提交地址
          if (problemId) {
            document.getElementById('deleteForm').action = `/admin/problems/delete/${problemId}`;
          }
          
          // 显示居中模态框
          deleteModal.show();
        });
      });
    });
  </script>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

  {% block scripts %}{% endblock %}
</body>
</html>
